from flask import Blueprint, render_template, request, jsonify

from applications.common import curd
from applications.common.utils.http import success_api, fail_api,table_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import LocationFinishedYP

from applications.schemas.admin_power import PowerSchema

bp = Blueprint('finished', __name__, url_prefix='/finished')


@bp.get('/yp/')
@authorize("location:finished:main:yp")
def index():
    return render_template('location/finished/yp/main.html')


@bp.post('/yp/data')
@authorize("location:finished:main:yp")
def data():


    query = db.session.query(
        LocationFinishedYP
    ).filter().layui_paginate()

    return table_api(
        data=[{
            'id': item.id,
            'name': item.name,
            'type': item.type,
            'code': item.code,
            'parent_id': item.parent_id,
            'icon': item.icon,
            'enable': item.enable,
            'sort': item.sort,

        } for item in query.items],
        count=query.total)


@bp.get('/yp/add')
@authorize("location:finished:add:yp", log=True)
def add():
    return render_template('location/finished/yp/add.html')


@bp.get('/yp/selectParent')
@authorize("location:finished:main:yp", log=True)
def select_parent():
    # power = Power.query.all()
    # res = curd.model_to_dicts(schema=PowerOutSchema2, data=power)

    raws=LocationFinishedYP.query.all()
    res=[]
    for raw in raws:
        res.append({
            'id':raw.id,
            'name':raw.name,
            'type':raw.type,
            'code': raw.code,
            'details': raw.details,
            'parent_id': raw.parent_id,
            'icon': raw.icon,
            'sort': raw.sort,
            'enable': raw.enable


        })
    res.append({"id": 0, "name": "顶级仓库", "parent_id": -1})
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": res

    }
    return jsonify(res)


# 增加
@bp.post('/yp/save')
@authorize("location:finished:add:yp", log=True)
def save():
    req = request.get_json(force=True)
    icon = str_escape(req.get("icon"))
    type = str_escape(req.get("type"))
    parent_id = str_escape(req.get("parent_id"))
    code = str_escape(req.get("code"))
    name = str_escape(req.get("name"))
    details = str_escape(req.get("details"))
    sort = str_escape(req.get("sort"))
    power = LocationFinishedYP(
        icon=icon,
        type=type,
        parent_id=parent_id,
        code=code,
        name=name,
        details=details,

        sort=sort,
        enable=1
    )
    r = db.session.add(power)
    try:
        db.session.commit()
        return success_api(msg="成功")
    except Exception as e:
        print(e)
        return fail_api(msg=f'失败，原因：{e}')

# 权限编辑
@bp.get('/yp/edit/<int:_id>')
@authorize("location:finished:edit:yp", log=True)
def edit(_id):
    power = curd.get_one_by_id(LocationFinishedYP, _id)
    icon = str(power.icon).split()
    if len(icon) == 2:
        icon = icon[1]
    else:
        icon = None
    return render_template('location/finished/yp/edit.html', power=power, icon=icon)


# 权限更新
@bp.put('/yp/update')
@authorize("location:finished:edit:yp", log=True)
def update():
    req_json = request.get_json(force=True)
    id = request.get_json(force=True).get("id")
    data = {
        "icon": str_escape(req_json.get("icon")),
        "type": str_escape(req_json.get("type")),
        "parent_id": str_escape(req_json.get("parent_id")),
        "code": str_escape(req_json.get("code")),
        "name": str_escape(req_json.get("name")),
        "details": str_escape(req_json.get("details")),

        "sort": str_escape(req_json.get("sort"))
    }

    try:
        res = LocationFinishedYP.query.filter_by(id=id).update(data)
        db.session.commit()
        if not res:
            return fail_api(msg="更新权限失败")
        return success_api(msg="更新权限成功")
    except Exception as e:
        print(e)
        return fail_api(msg=f'失败，原因：{e}')

# 启用权限
@bp.put('/yp/enable')
@authorize("location:finished:edit:yp", log=True)
def enable():
    _id = request.get_json(force=True).get('id')
    if id:
        res = curd.enable_status(LocationFinishedYP, _id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启用成功")
    return fail_api(msg="数据错误")


# 禁用权限
@bp.put('/yp/disable')
@authorize("location:finished:edit:yp", log=True)
def dis_enable():
    _id = request.get_json(force=True).get('id')
    if id:
        res = curd.disable_status(LocationFinishedYP, _id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")


# 权限删除
@bp.delete('/yp/remove/<int:id>')
@authorize("location:finished:remove:yp", log=True)
def remove(id):
    t = LocationFinishedYP.query.filter_by(parent_id=id).delete()
    r = LocationFinishedYP.query.filter_by(id=id).delete()
    db.session.commit()
    if r:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg="删除失败")